﻿using System;
using EasyLib.Utils;

namespace EasyLib.Extensions
{
    public static class StringExtensions
    {
        public static bool IsNullOrBlank(this string str)
        {
            return str == null || str.Trim().Length == 0;
        }

        public static string Null2Blank(this string str)
        {
            return str ?? string.Empty;
        }

        /// <summary>
        /// 将字符串分割为指定类型的数组
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="value"></param>
        /// <param name="separator"></param>
        /// <returns></returns>
        public static T[] Split2Array<T>(this string value, string separator)
        {
            if (value == null) return null;
            string[] eles = value.Split(new[] { separator }, StringSplitOptions.None);
            T[] destArr = new T[eles.Length];
            for (int i = 0; i < eles.Length; i++)
            {
                string e = typeof(T) == typeof(string) ? eles[i] : (eles[i].IsNullOrBlank() ? null : eles[i].Trim());
                destArr[i] = TypeConvertUtils.ConvertType<T>(e);
            }
            return destArr;
        }

        public static T[] Split2Array<T>(this string value)
        {
            const string separator = ",";
            return value.Split2Array<T>(separator);
        }

        public static string FormatWith(this string str, params object[] os)
        {
            if (str.IsNullOrBlank() || os == null || os.Length == 0) return str;
            os = Array.FindAll(os, o => o != null);
            return string.Format(str, os);
        }
    }
}
